public class BinarySearchTree {
    static class TreeNode{
        public int val;
        public TreeNode left;
        public TreeNode right;

        public TreeNode(int val){
            this.val = val;
        }
    }

    public TreeNode root = null;

    public boolean search(int val){
        TreeNode cur = root;

        while(cur != null){
            if(cur.val < val){
                cur = cur.right;
            }else if(cur.val > val){
                cur = cur.left;
            }else{
                return true;
            }
        }
        return false;
    }

    public boolean insert(int val){
        TreeNode node = new TreeNode(val);
        if(root == null){
            root = node;
            return true;
        }

        TreeNode parent = null;
        TreeNode cur = root;
        while(cur != null){
            if(cur.val < val){
                parent = cur;
                cur = cur.right;
            }else if(cur.val > val){
                parent = cur;
                cur = cur.left;
            }else{
                return false;
            }
        }

        if(parent.val < val){
            parent.right = node;
        }else{
            parent.left = node;
        }
        return true;
    }

    public void remove(int val){
        TreeNode cur = root;
        TreeNode parent = null;

        while(cur != null){
            if(cur.val > val){
                parent = cur;
                cur = cur.left;
            }else if(cur.val < val){
                parent = cur;
                cur = cur.right;
            }else{
                removeNode(parent, cur);
            }
        }
    }

    private void removeNode(TreeNode parent, TreeNode cur){
        if(cur.left == null){
            if(cur == root){
                root = cur.right;
            }else if(cur == parent.left){
                parent.left = cur.right;
            }else{
                parent.right = cur.right;
            }
        }else if(cur.right == null){
            if(cur == root){
                root = cur.left;
            }else if(cur == parent.left){
                parent.left = cur.left;
            }else{
                parent.right = cur.left;
            }
        }else{
            TreeNode tp = cur;
            TreeNode t = cur.right;
            while(t.left != null){
                tp = t;
                t = t.left;
            }
            cur.val = t.val;
            if(tp.right == t){
                tp.right = t.right;
            }else{
                tp.left = t.right;
            }
        }
    }
}
